import Vue from "vue";
import App from "./App";
import store from "./store";
import router from "./router";
import axios from "axios";
import NProgress from "nprogress"; // Progress 进度条
import "nprogress/nprogress.css"; // Progress 进度条样式
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css"; // 默认主题
//import '../static/css/theme-green/index.css';       // 浅绿色主题
import "../static/css/icon.css";
import "babel-polyfill";
import { getToken } from "@/utils/auth"; // 验权
import has from "@/utils/btnPermissions"; // 按钮权限
import permissions from "@/utils/Permissions"; // 按钮权限

Vue.use(ElementUI, { size: "small" });
Vue.prototype.$axios = axios;
Vue.prototype.$permissions = permissions;

const whiteList = ["/login", "/404", "/403"]; // 不重定向白名单
router.beforeEach((to, from, next) => {
  const title = to.meta.title || "接口管理平台";
  document.title = title;
  NProgress.start();
  if (getToken()) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done(); // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.roles.length === 0) {
        store
          .dispatch("GetInfo")
          .then(res => {
            // 拉取用户信息
            if(to.path === "/"){
              next({ path: "/api" });
              NProgress.done();
            }else if (to.path === "/api" || to.path === "/notice") {
              next();
              NProgress.done();
            }else if(store.getters.menus.indexOf(to.path) !== -1){
              next();
              NProgress.done();
            }else{
              next({ path: "/403" });
              NProgress.done();
            }
          })
          .catch(() => {
            next({ path: "/login" });
            NProgress.done();
          });
      } else {
        if(to.path === "/"){
          next({ path: "/api" });
          NProgress.done();
        }else if (to.path === "/api" || to.path === "/notice") {
          next();
          NProgress.done();
        }else if (store.getters.menus.indexOf(to.path) > 0) {
          next();
          NProgress.done();
        } else {
          if (whiteList.indexOf(to.path) !== -1) {
            next();
            NProgress.done();
          } else {
            next({ path: "/403" });
            NProgress.done();
          }
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
      NProgress.done();
    } else {
      next({ path: "/login" });
      NProgress.done();
    }
  }
});

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");
